<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章名称" prop="title" style="width: 400px">
            <el-input v-model="form.title" placeholder="请输入文章名称" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="文章分类" prop="type" style="width: 400px">
            <el-cascader v-loading="placeTypeLoading" v-model="form.type" placeholder="请选择文章分类"
                         :options="placeTypeOption"
                         :show-all-levels="false"
                         :props="{value:'id',label:'name',children:'child'}"
                         @change="handleChange"
                         filterable
            ></el-cascader>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章封面" prop="Abstract" style="width: 800px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.imaUrl" :src="form.imaUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="form.imaUrl" alt="">
        </el-dialog>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章摘要" prop="Abstract" style="width: 800px">
            <el-input type="textarea" v-model="form.abstract" placeholder="请输入摘要"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章内容" prop="Abstract">
            <div class="container">
              <Toolbar :editor="editor" :default-config="toolbarConfig" :mode="mode"/>
              <Editor v-model="form.content" :default-config="editorConfig" :mode="mode" @onCreated="onCreated"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {getNewsByIdApi, getNewsTypeNameApi, insertAndUpdateNewsApi} from '@/api/placeCode'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {getIncubatorsArticleByFatherIdApi} from "@/api/entrepreneurship";
import axios from "axios";
import {uploadApi} from "@/api/user";

export default {
  components: {Editor, Toolbar},
  name: 'PlaceCodeDetail',
  data() {
    return {
      editor: null,
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: { MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            customUpload: this.uploadImageMe // this.uploadImageMe 是 methods 中的一个普通方法
          },
        },
        placeholder: ''
      },
      mode: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      form: {
        id: null,
        abstract: '',
        title: '',
        content: '',
        imaUrl: '',
        type: ''
      },
      rules: {
        title: [{required: true, trigger: 'blur', message: '请输入文章标题'}],
        abstract: [{required: true, trigger: 'blur', message: '请输入文章摘要'}],
        content: [{required: true, trigger: 'blur', message: '请输入内容'}],
        type: [{required: true, trigger: 'blur', message: '请选择文章分类'}],
      },
      formLoading: false,
      placeTypeLoading: true,
      placeTypeOption: [],
    }
  },
  props: ['id', 'closeDialog'],
  methods: {
    //上传文件配置
    uploadImageMe(file, insertFn){
      // file 即选中的文件
      // 自己实现上传，并得到图片 url alt href
      let name = file.name;
      let suffix = file.type.split("/")[1];
      name = name + '.' + suffix;
      let formdata = new FormData()
      formdata.append("file", file)
      //上传方法
      uploadApi(formdata).then(res => {
        console.log(res)
        // 最后插入图片
        insertFn(res , res, res )
      })

    },
    handleChange(value) {
      console.log(value);
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleAvatarSuccess(res, file) {
      this.form.imaUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    getPlaceType() {
      getNewsTypeNameApi().then((res) => {
        this.placeTypeOption = res;
      }).catch((err) => {
        this.$message.error('场所分类加载失败，请重试')
      }).finally(() => {
        this.placeTypeLoading = false;
      })
    },
    submit() {
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            text: '提交中'
          })
          if (this.form.id == null) {
            this.form.id = 0;
          }
          const form = JSON.parse(JSON.stringify(this.form));
          console.log(this.form.type.length)
          if (typeof this.form.type !== 'number') {
            if (this.form.type.length === 1) {
              form.type = this.form.type[0];
            }
            if (this.form.type.length === 2) {
              form.type = this.form.type[1];
            }
          }
          insertAndUpdateNewsApi(form).then((res) => {
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch(() => {
            this.$message.error('保存失败');
          }).finally(() => {
            loading.close();
          })
        } else {
          return false
        }
      })
    },
    getDetail() {
      this.formLoading = true;
      getNewsByIdApi({id: this.id}).then((res) => {
        this.form = res;
        this.form.type = 1;
      }).finally(() => {
        this.formLoading = false;
      })
    },
  },
  mounted() {
    if (this.id) {
      this.getDetail();
    }
    this.getPlaceType();
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.w-e-bar.w-e-bar-show.w-e-toolbar {
  border: 1px solid;
}

.w-e-scroll {
  border: 1px solid;
}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select, .el-cascader {
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
